﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using YBBEST.Office365Portal.Core.SPListWS;
using YBBEST.Office365Portal.Core.SPMeetingWS;

namespace YBBEST.Office365Portal.Core
{
    public class MeetingRepository : IMeetingRepository
    {
        private readonly string username;
        private readonly string password;
        private readonly string siteUrl;

        public MeetingRepository(IProxyConfiguration configuration)
        {
             username = configuration.Username;
             password = configuration.Password;
             siteUrl = configuration.SiteUrl;
        }

        public void CreateNewSite(string siteName, string siteTemplate )
        {
            string meetingsAsmxEndpoint = string.Format("{0}_vti_bin/Meetings.asmx", siteUrl);
            var httpReqMessFedCookieProp = BuildHttpReqMessFedCookieProp();
            using (var proxy = new MeetingsSoapClient())
            {
                proxy.Endpoint.Address = new EndpointAddress(meetingsAsmxEndpoint);
                using (new OperationContextScope(proxy.InnerChannel))
                {
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpReqMessFedCookieProp;
                    proxy.CreateWorkspace(siteName, siteTemplate, 1033, new TimeZoneInf { daylightDate = new SysTime(), standardDate = new SysTime() });
                }
            }
        }

        public void DeleteSite()
        {
            string meetingsAsmxEndpoint = string.Format("{0}_vti_bin/Meetings.asmx", siteUrl);
            var httpReqMessFedCookieProp = BuildHttpReqMessFedCookieProp();
            using (var proxy = new MeetingsSoapClient())
            {
                proxy.Endpoint.Address = new EndpointAddress(meetingsAsmxEndpoint);
                using (new OperationContextScope(proxy.InnerChannel))
                {
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpReqMessFedCookieProp;
                    proxy.DeleteWorkspace();
                }
            }
        }

        //TODO: Extract this out to a class and inject using ninject
        public HttpRequestMessageProperty BuildHttpReqMessFedCookieProp()
        {
            var claimsHelper = new MsOnlineClaimsHelper(username, password, siteUrl);
            var p = new HttpRequestMessageProperty();
            var cookie = claimsHelper.CookieContainer;
            string cookieHeader = cookie.GetCookieHeader(new Uri(siteUrl));
            p.Headers.Add("Cookie", cookieHeader);
            return p;
        }
    }
}
